package com.controller;

import com.google.gson.Gson;
import com.pojo.Enterprise;
import com.pojo.User;
import com.pojo.SupplierWhiteList;
import com.pojo.SupplierBlackList;
import com.service.IEnterpriseService;
import com.service.ISupplierWhiteListService;
import com.service.ISupplierBlackListService;
import com.service.IUserService;
import com.service.impl.EnterpriseServiceImpl;
import com.service.impl.SupplierWhiteListServciceImpl;
import com.service.impl.SupplierBlackListServciceImpl;
import com.service.impl.UserServiceImpl;
import com.util.PageHelper;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;

@WebServlet("/whitelist/*")
public class SupplierWhiteListController extends HttpServlet {
    private ISupplierWhiteListService whiteListService = new SupplierWhiteListServciceImpl();
    private ISupplierBlackListService blackListService = new SupplierBlackListServciceImpl();
    private IUserService userService = new UserServiceImpl();
    private IEnterpriseService enterpriseService = new EnterpriseServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        int index = requestURI.lastIndexOf("/") + 1;
        String methodName = requestURI.substring(index);

        // 设置响应头
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("方法不存在或调用失败"));
        }
    }

    /**
     * 分页查询当前登录用户关联企业的供应商白名单列表
     * 核心逻辑：先验证用户登录状态与企业关联状态，再分页查询白名单，最后补充供应商企业详情
     */
    public void getWhiteListByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 1. 验证用户登录状态：从Session中获取当前登录用户账号（登录时存入Session的"loginUser"）
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;// 未登录，终止流程
            }

            // 2. 验证用户是否关联企业：通过账号查询用户信息，检查enterpriseId是否存在
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 3. 获取分页参数：pageIndex（当前页码），默认值为1
            String pageIndexStr = request.getParameter("pageIndex");
            Integer pageIndex = (pageIndexStr != null && !pageIndexStr.isEmpty()) ? Integer.parseInt(pageIndexStr) : 1;

            // 4. 分页查询白名单：传入当前用户关联的企业ID和页码，返回分页助手对象（含列表数据、总条数等）
            PageHelper pageHelper = whiteListService.getWhiteListByPage(user.getEnterpriseId(), pageIndex);

            // 5. 处理白名单数据：补充供应商企业详情（名称、联系方式等），构建前端所需格式
            ArrayList<SupplierWhiteList> whiteList = (ArrayList<SupplierWhiteList>) pageHelper.getListIndex();
            ArrayList<Map<String, Object>> detailedList = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 日期格式化（统一返回格式）
            // 遍历白名单，为每条记录补充供应商信息
            for (SupplierWhiteList item : whiteList) {
                Map<String, Object> detailMap = new HashMap<>();
                // 存入白名单基础字段
                detailMap.put("id", item.getId()); // 白名单记录ID
                detailMap.put("enterpriseId", item.getEnterpriseId());// 当前用户关联企业ID
                detailMap.put("supplierId", item.getSupplierId());// 供应商企业ID
                detailMap.put("supplierLevel", item.getSupplierLevel());// 供应商等级
                // 日期格式化：null时返回空字符串，避免前端报错
                detailMap.put("updateDate", item.getUpdateDate() != null ? dateFormat.format(item.getUpdateDate()) : "");

                // 6. 查询供应商企业详情：通过supplierId获取企业信息
                Enterprise supplier = enterpriseService.getEnterpriseById(item.getSupplierId());
                if (supplier != null) {
                    detailMap.put("supplierName", supplier.getName());// 供应商名称
                    detailMap.put("supplierContact", supplier.getName());// 临时用企业名称作为联系人
                    detailMap.put("supplierPhone", supplier.getPhone());// 供应商电话
                    detailMap.put("supplierEmail", supplier.getEmail()); // 供应商邮箱
                    detailMap.put("supplierSocialUniformCode", supplier.getSocialUniformCode());// 供应商统一社会信用代码
                } else {
                    // 供应商不存在（可能已删除），填充默认值
                    detailMap.put("supplierName", "未知企业");
                    detailMap.put("supplierContact", "-");
                    detailMap.put("supplierPhone", "-");
                    detailMap.put("supplierEmail", "-");
                    detailMap.put("supplierSocialUniformCode", "-");
                }
                
                detailedList.add(detailMap); // 将处理后的记录加入列表
            }

            // 7. 构建分页返回结果：包含数据列表、总条数、当前页、总页数
            Map<String, Object> result = new HashMap<>();
            result.put("data", detailedList);// 白名单详细列表
            result.put("totalCount", pageHelper.getDataCount()); // 总记录数
            result.put("currentPage", pageHelper.getPageIndex()); // 当前页码
            result.put("totalPages", pageHelper.getPageCount());// 总页数
            // 8. 向客户端返回结果（JSON格式
            response.getWriter().println(new Gson().toJson(result));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("查询白名单失败"));
        }
    }

    /**
     * 按条件搜索白名单（支持企业名称和企业评级筛选）
     */
    public void searchWhiteList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取搜索参数
            String supplierName = request.getParameter("supplierName");
            String supplierLevel = request.getParameter("supplierLevel");
            String pageIndexStr = request.getParameter("pageIndex");
            Integer pageIndex = (pageIndexStr != null && !pageIndexStr.isEmpty()) ? Integer.parseInt(pageIndexStr) : 1;

            // 条件搜索
            PageHelper pageHelper = whiteListService.searchWhiteListByCondition(
                    user.getEnterpriseId(), supplierName, supplierLevel, pageIndex);
            
            // 获取详细信息
            ArrayList<SupplierWhiteList> whiteList = (ArrayList<SupplierWhiteList>) pageHelper.getListIndex();
            ArrayList<Map<String, Object>> detailedList = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            
            for (SupplierWhiteList item : whiteList) {
                Map<String, Object> detailMap = new HashMap<>();
                detailMap.put("id", item.getId());
                detailMap.put("enterpriseId", item.getEnterpriseId());
                detailMap.put("supplierId", item.getSupplierId());
                detailMap.put("supplierLevel", item.getSupplierLevel());
                detailMap.put("updateDate", item.getUpdateDate() != null ? dateFormat.format(item.getUpdateDate()) : "");
                
                // 获取供应商企业信息
                Enterprise supplier = enterpriseService.getEnterpriseById(item.getSupplierId());
                if (supplier != null) {
                    detailMap.put("supplierName", supplier.getName());
                    detailMap.put("supplierContact", supplier.getName()); // 使用企业名称作为联系人
                    detailMap.put("supplierPhone", supplier.getPhone());
                    detailMap.put("supplierEmail", supplier.getEmail());
                    detailMap.put("supplierSocialUniformCode", supplier.getSocialUniformCode());
                } else {
                    detailMap.put("supplierName", "未知企业");
                    detailMap.put("supplierContact", "-");
                    detailMap.put("supplierPhone", "-");
                    detailMap.put("supplierEmail", "-");
                    detailMap.put("supplierSocialUniformCode", "-");
                }
                
                detailedList.add(detailMap);
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("data", detailedList);
            result.put("totalCount", pageHelper.getDataCount());
            result.put("currentPage", pageHelper.getPageIndex());
            result.put("totalPages", pageHelper.getPageCount());
            
            response.getWriter().println(new Gson().toJson(result));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("搜索白名单失败"));
        }
    }

    /**
     * 添加供应商到白名单
     */
    public void addToWhiteList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取参数
            String supplierIdStr = request.getParameter("supplierId");
            String supplierLevel = request.getParameter("supplierLevel");

            if (supplierIdStr == null || supplierLevel == null) {
                response.getWriter().println(new Gson().toJson("参数不完整"));
                return;
            }

            Integer supplierId = Integer.parseInt(supplierIdStr);

            // 检查是否已在白名单中
            if (whiteListService.isInWhiteList(user.getEnterpriseId(), supplierId)) {
                response.getWriter().println(new Gson().toJson("该供应商已在白名单中"));
                return;
            }

            // 创建白名单记录
            SupplierWhiteList whiteList = new SupplierWhiteList();
            whiteList.setEnterpriseId(user.getEnterpriseId());
            whiteList.setSupplierId(supplierId);
            whiteList.setSupplierLevel(supplierLevel);
            whiteList.setUpdateDate(new Date());

            // 添加到白名单
            boolean success = whiteListService.addWhiteList(whiteList);
            
            if (success) {
                response.getWriter().println(new Gson().toJson("添加成功"));
            } else {
                response.getWriter().println(new Gson().toJson("添加失败"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("添加白名单失败"));
        }
    }

    /**
     * 从白名单移除供应商（移至黑名单）
     */
    public void removeFromWhiteList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取参数
            String supplierIdStr = request.getParameter("supplierId");
            String reason = request.getParameter("reason");
            
            if (supplierIdStr == null) {
                response.getWriter().println(new Gson().toJson("参数不完整"));
                return;
            }
            
            // 如果没有提供原因，使用默认原因
            if (reason == null || reason.trim().isEmpty()) {
                reason = "从白名单移至黑名单";
            }

            Integer supplierId = Integer.parseInt(supplierIdStr);

            // 检查是否已在黑名单中
            if (blackListService.isInBlackList(user.getEnterpriseId(), supplierId)) {
                response.getWriter().println(new Gson().toJson("该供应商已在黑名单中"));
                return;
            }

            // 从白名单删除
            boolean removeSuccess = whiteListService.delBlackList(user.getEnterpriseId(), supplierId);
            
            if (removeSuccess) {
                // 添加到黑名单
                SupplierBlackList blackList = new SupplierBlackList();
                blackList.setEnterpriseId(user.getEnterpriseId());
                blackList.setSupplierId(supplierId);
                blackList.setReason(reason.trim());
                blackList.setUpdateDate(new Date());
                
                boolean addSuccess = blackListService.addBlackList(blackList);
                
                if (addSuccess) {
                    response.getWriter().println(new Gson().toJson("已成功移至黑名单"));
                } else {
                    // 如果添加黑名单失败，需要回滚白名单的删除操作
                    // 但由于没有回滚机制，先返回部分成功的信息
                    response.getWriter().println(new Gson().toJson("从白名单移除成功，但添加到黑名单失败"));
                }
            } else {
                response.getWriter().println(new Gson().toJson("从白名单移除失败"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("移至黑名单操作失败"));
        }
    }

    /**
     * 获取可添加的企业列表（不在当前白名单中的企业）
     */
    public void getAvailableEnterprises(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取所有企业
            ArrayList<Enterprise> allEnterprises = enterpriseService.getAllEnterprises();
            ArrayList<Map<String, Object>> availableEnterprises = new ArrayList<>();
            
            for (Enterprise enterprise : allEnterprises) {
                // 排除自己的企业，并检查是否已在白名单中
                if (!enterprise.getId().equals(user.getEnterpriseId()) && 
                    !whiteListService.isInWhiteList(user.getEnterpriseId(), enterprise.getId())) {
                    
                    Map<String, Object> enterpriseMap = new HashMap<>();
                    enterpriseMap.put("id", enterprise.getId());
                    enterpriseMap.put("name", enterprise.getName());
                    enterpriseMap.put("creditCode", enterprise.getSocialUniformCode());
                    enterpriseMap.put("contact", enterprise.getName()); // 使用企业名称作为联系人
                    enterpriseMap.put("phone", enterprise.getPhone());
                    enterpriseMap.put("email", enterprise.getEmail());
                    
                    availableEnterprises.add(enterpriseMap);
                }
            }
            
            response.getWriter().println(new Gson().toJson(availableEnterprises));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("获取可用企业列表失败"));
        }
    }
}